# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient


class SpiderPipeline(object):
    def __init__(self):
        self.client = MongoClient('127.0.0.1', 27017)

    def open_spider(self, spider):
        if spider.name == 'mmonly_tag':
            collection = self.client['spider_mmonly']['tag']
            collection.delete_many({})
        elif spider.name == 'mmonly_group_list':
            collection = self.client['spider_mmonly']['group_list']
            collection.delete_many({})
        elif spider.name == 'mmonly_group_image':
            collection = self.client['spider_mmonly']['group_image']
            collection.delete_many({})

    def process_item(self, item, spider):
        print(item)
        if spider.name == 'mmonly_tag':
            collection = self.client['spider_mmonly']['tag']
            collection.insert_one(item)
        elif spider.name == 'mmonly_group_list':
            collection = self.client['spider_mmonly']['group_list']
            collection.insert_one(item)
        elif spider.name == 'mmonly_group_image':
            collection = self.client['spider_mmonly']['group_image']
            collection.insert_one(item)
        return item
